<?php

namespace App\Http\Controllers\Guard\Rbac;

use App\Http\Controllers\Common\GuardController;
use App\Models\Constant\Constant;
use App\Models\Rbac\GuardUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class GuardUserController extends GuardController {

    public function __construct() {
        $this->instance = new GuardUser();
    }

    public function getGuardUser(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $guardUser = $this->instance->getRecordById($id);
        $guardUser->has_permission = $guardUser->hasPermissions();
        return responseSuccess($guardUser->toArray());
    }

    public function lst(Request $request) {
        $name   = $request->input('name');
        $phone  = $request->input('phone');
        $page  = $request->input('page',1);
        $limit  = $request->input('limit',Constant::PAGE_SIZE);
        $conditions = compact('name','phone');
        $records = $this->instance->getLst($conditions)->paginate($limit,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $info = $request->input();
        $id = $request->input('id',0);
        $this->validate($request, [
            'name'=>'required',
        ],[],[
            'name'=>'用户名',
        ]);

        $info['role_ids'] = implode(',', $info['selectRoleIds']);
        try{
            //id小于等于0，说明是新增操作
            if($id<=0){
                //检查用户名是否存在
                if(!empty((new GuardUser())->getUserByName($info['name'])))
                    return responseFail(300000);
                $info['password'] = md5($info['password']);
            }
            else{
                //如果是修改操作
                unset($info['password']);
            }
            unset($info['selectRoleIds']);
            unset($info['repassword']);
            $this->instance->updateOrCreate(compact('id'),$info);
            return responseSuccess();
        }catch(\Exception $e){
            $msg = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($msg);
            return responseFail($msg);
        }
    }

    public function edit(Request $request){
        $id = $request->input('id',0);
        $info = $request->except('id');
        $this->validate($request, ['id'=>'required|Integer']);
       $this->instance->updateOrCreate(compact('id'),$info);
        return responseSuccess();
    }

    public function modifyPassword(Request $request) {
        $oldPassword = $request->input('oldPassword');
        $password = $request->input('password');

        $this->validate($request, [
            'oldPassword'=>'required',
            'password'=>'required|confirmed',
        ],[],[
            'oldPassword'=>'原密码'
        ]);

        $token = $request->header('token');
        $id = checkJWT($token)['id'];

        $user = (new GuardUser())->getRecordById($id);
        if(empty($user)){
            return responseFail('无效用户');
        }
        if($user->password!=md5($oldPassword)){
            return responseFail('原密码错误！');
        }
        $user->password = md5($password);
        $user->save();
        return responseSuccess();
    }

    /**
     * SuperAdmin强制重置密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function coverPassword(Request $request) {
        $id = $request->input('id',0);
        $password = $request->input('value',0);
        $this->instance->newQuery()->where(compact('id'))->update(['password'=>md5($password)]);
        return responseSuccess([],0,'重置成功，新密码为：'.$password);
    }


}
